{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "aca95a33",
   "metadata": {},
   "source": [
    "# 经典图论\n",
    "\n",
    "无向图\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d2b0b086",
   "metadata": {},
   "outputs": [],
   "source": [
    "def MaxAreaIfIsland(grid):\n",
    "    row = len(grid)\n",
    "    col = len(grid[0]) # 记录二维数组的列数，也是地图上的x轴长度\n",
    "    arrived = [[False for j in range(col)] for i in range(row)]\n",
    "    \n",
    "    ans = 0\n",
    "    return ans\n",
    "\n",
    "# 深度优先代码\n",
    "def DFS(x, y, grid):\n",
    "    row = len(grid)\n",
    "    col = len(grid[0])\n",
    "    arrived = [[False for j in range(col) for i in range(row)]]\n",
    "    \n",
    "    ans = 0\n",
    "    \n",
    "    if x >= 0 and x < row and y >= 0 and y < col and not arrived[x][y] and grid[x][y] == 1:\n",
    "        arrived[x][y] = True\n",
    "        return 1 + DFS(x - 1, y) + DFS(x+1, y) + DFS(x, y-1) + DFS(x, y+1)\n",
    "    else:\n",
    "        return 0\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "81ecf23a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def MaxAreaIfIsland(grid):\n",
    "    row = len(grid)\n",
    "    col = len(grid[0]) # 记录二维数组的列数，也是地图上的x轴长度\n",
    "    arrived = [[False for j in range(col)] for i in range(row)]\n",
    "    \n",
    "    ans = 0\n",
    "\n",
    "    # 深度优先代码\n",
    "    def DFS(x, y, grid):\n",
    "        row = len(grid)\n",
    "        col = len(grid[0])\n",
    "        arrived = [[False for j in range(col) for i in range(row)]]\n",
    "\n",
    "        ans = 0\n",
    "\n",
    "        if x >= 0 and x < row and y >= 0 and y < col and not arrived[x][y] and grid[x][y] == 1:\n",
    "            arrived[x][y] = True\n",
    "            return 1 + DFS(x - 1, y) + DFS(x+1, y) + DFS(x, y-1) + DFS(x, y+1)\n",
    "        else:\n",
    "            return 0\n",
    "        \n",
    "    \n",
    "    for i in range(row):\n",
    "        for j in range(col):\n",
    "            area = DFS(i, j)\n",
    "            \n",
    "            if area > ans:\n",
    "                ans = area\n",
    "                \n",
    "    return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e1eafdc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "trader",
   "language": "python",
   "name": "trader"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
